/**
 * PowerUpGenerator - 道具生成器
 * 负责在游戏过程中动态生成道具
 */

import { PowerUpFactory } from './PowerUpFactory'
import { PowerUp, PowerUpType } from './PowerUp'
import type { EntityManager } from './EntityManager'

/**
 * 道具生成模式
 */
export enum PowerUpSpawnPattern {
  RANDOM = 'random',           // 随机生成
  SEQUENCE = 'sequence',       // 序列生成
  CLUSTER = 'cluster',         // 集群生成
  ALTERNATING = 'alternating'  // 交替生成
}

/**
 * 道具生成配置
 */
export interface PowerUpGeneratorConfig {
  spawnPattern: PowerUpSpawnPattern
  baseSpawnRate: number        // 基础生成率（每秒）
  spawnRateIncrease: number    // 生成率递增（每级）
  minSpawnDistance: number     // 最小生成距离
  maxSpawnDistance: number     // 最大生成距离
  spawnHeight: number          // 生成高度
  spawnLanes: number[]         // 可生成的车道
  clusterSize: number          // 集群大小
  sequenceLength: number       // 序列长度
}

/**
 * 道具生成状态
 */
interface GeneratorState {
  lastSpawnTime: number
  lastSpawnX: number
  currentLevel: number
  totalDistance: number
  spawnCount: number
  currentSequence: PowerUpType[]
  sequenceIndex: number
  clusterRemaining: number
}

/**
 * 道具生成器类
 */
export class PowerUpGenerator {
  private factory: PowerUpFactory
  private entityManager: EntityManager | null = null
  private config: PowerUpGeneratorConfig
  private state: GeneratorState
  private enabled: boolean = true

  constructor(config?: Partial<PowerUpGeneratorConfig>) {
    this.factory = PowerUpFactory.getInstance()
    
    // 默认配置
    this.config = {
      spawnPattern: PowerUpSpawnPattern.RANDOM,
      baseSpawnRate: 0.3, // 每秒0.3个道具
      spawnRateIncrease: 0.05, // 每级增加0.05
      minSpawnDistance: 300, // 最小间距300像素
      maxSpawnDistance: 800, // 最大间距800像素
      spawnHeight: 200, // 生成高度
      spawnLanes: [0, 1, 2], // 三个车道
      clusterSize: 3, // 集群包含3个道具
      sequenceLength: 5, // 序列长度为5
      ...config
    }

    // 初始化状态
    this.state = {
      lastSpawnTime: 0,
      lastSpawnX: 0,
      currentLevel: 1,
      totalDistance: 0,
      spawnCount: 0,
      currentSequence: [],
      sequenceIndex: 0,
      clusterRemaining: 0
    }
  }

  /**
   * 设置实体管理器
   */
  setEntityManager(entityManager: EntityManager): void {
    this.entityManager = entityManager
  }

  /**
   * 更新道具生成器
   * @param deltaTime - 时间差
   * @param playerX - 玩家X坐标
   * @param level - 当前等级
   * @param distance - 总距离
   */
  update(deltaTime: number, playerX: number, level: number, distance: number): void {
    if (!this.enabled || !this.entityManager) {
      return
    }

    // 更新状态
    this.state.currentLevel = level
    this.state.totalDistance = distance

    // 检查是否应该生成道具
    if (this.shouldSpawnPowerUp(deltaTime, playerX)) {
      this.spawnPowerUp(playerX)
    }
  }

  /**
   * 启用/禁用道具生成
   */
  setEnabled(enabled: boolean): void {
    this.enabled = enabled
  }

  /**
   * 重置生成器状态
   */
  reset(): void {
    this.state = {
      lastSpawnTime: 0,
      lastSpawnX: 0,
      currentLevel: 1,
      totalDistance: 0,
      spawnCount: 0,
      currentSequence: [],
      sequenceIndex: 0,
      clusterRemaining: 0
    }
  }

  /**
   * 更新生成配置
   */
  updateConfig(config: Partial<PowerUpGeneratorConfig>): void {
    this.config = { ...this.config, ...config }
  }

  /**
   * 获取当前配置
   */
  getConfig(): PowerUpGeneratorConfig {
    return { ...this.config }
  }

  /**
   * 获取生成器状态
   */
  getState(): GeneratorState {
    return { ...this.state }
  }

  /**
   * 手动生成道具
   * @param x - X坐标
   * @param type - 道具类型（可选）
   * @returns 生成的道具
   */
  manualSpawn(x: number, type?: PowerUpType): PowerUp | null {
    if (!this.entityManager) {
      return null
    }

    const lane = this.getRandomLane()
    const y = this.config.spawnHeight
    const laneX = this.getLaneX(x, lane)

    let powerUp: PowerUp | null = null

    if (type) {
      powerUp = this.factory.createPowerUp(type, laneX, y)
    } else {
      powerUp = this.factory.createRandomPowerUp(laneX, y, this.state.currentLevel)
    }

    if (powerUp) {
      this.entityManager.addEntity(powerUp)
      this.state.spawnCount++
    }

    return powerUp
  }

  /**
   * 检查是否应该生成道具
   */
  private shouldSpawnPowerUp(_deltaTime: number, playerX: number): boolean {
    const currentTime = Date.now()
    const timeSinceLastSpawn = currentTime - this.state.lastSpawnTime
    
    // 计算当前生成率
    const currentSpawnRate = this.config.baseSpawnRate + 
                           (this.state.currentLevel - 1) * this.config.spawnRateIncrease
    
    // 计算生成间隔（毫秒）
    const spawnInterval = 1000 / currentSpawnRate
    
    // 检查时间间隔
    if (timeSinceLastSpawn < spawnInterval) {
      return false
    }

    // 检查距离间隔
    const distanceSinceLastSpawn = playerX - this.state.lastSpawnX
    if (distanceSinceLastSpawn < this.config.minSpawnDistance) {
      return false
    }

    // 使用工厂的概率检查
    return this.factory.shouldSpawnPowerUp(this.state.currentLevel)
  }

  /**
   * 生成道具
   */
  private spawnPowerUp(playerX: number): void {
    if (!this.entityManager) {
      return
    }

    const spawnX = playerX + this.getSpawnDistance()
    
    switch (this.config.spawnPattern) {
      case PowerUpSpawnPattern.RANDOM:
        this.spawnRandomPowerUp(spawnX)
        break
        
      case PowerUpSpawnPattern.SEQUENCE:
        this.spawnSequencePowerUp(spawnX)
        break
        
      case PowerUpSpawnPattern.CLUSTER:
        this.spawnClusterPowerUp(spawnX)
        break
        
      case PowerUpSpawnPattern.ALTERNATING:
        this.spawnAlternatingPowerUp(spawnX)
        break
    }

    // 更新状态
    this.state.lastSpawnTime = Date.now()
    this.state.lastSpawnX = spawnX
  }

  /**
   * 随机生成道具
   */
  private spawnRandomPowerUp(x: number): void {
    const lane = this.getRandomLane()
    const y = this.config.spawnHeight
    const laneX = this.getLaneX(x, lane)

    const powerUp = this.factory.createRandomPowerUp(laneX, y, this.state.currentLevel)
    if (powerUp && this.entityManager) {
      this.entityManager.addEntity(powerUp)
      this.state.spawnCount++
    }
  }

  /**
   * 序列生成道具
   */
  private spawnSequencePowerUp(x: number): void {
    // 如果序列为空或已完成，生成新序列
    if (this.state.currentSequence.length === 0 || this.state.sequenceIndex >= this.state.currentSequence.length) {
      this.generateNewSequence()
      this.state.sequenceIndex = 0
    }

    const type = this.state.currentSequence[this.state.sequenceIndex]
    const lane = this.getRandomLane()
    const y = this.config.spawnHeight
    const laneX = this.getLaneX(x, lane)

    const powerUp = this.factory.createPowerUp(type, laneX, y)
    if (powerUp && this.entityManager) {
      this.entityManager.addEntity(powerUp)
      this.state.spawnCount++
      this.state.sequenceIndex++
    }
  }

  /**
   * 集群生成道具
   */
  private spawnClusterPowerUp(x: number): void {
    if (this.state.clusterRemaining <= 0) {
      this.state.clusterRemaining = this.config.clusterSize
    }

    const lane = this.getRandomLane()
    const y = this.config.spawnHeight
    const laneX = this.getLaneX(x, lane)

    const powerUp = this.factory.createRandomPowerUp(laneX, y, this.state.currentLevel)
    if (powerUp && this.entityManager) {
      this.entityManager.addEntity(powerUp)
      this.state.spawnCount++
      this.state.clusterRemaining--
    }
  }

  /**
   * 交替生成道具
   */
  private spawnAlternatingPowerUp(x: number): void {
    const availableTypes = this.factory.getAvailablePowerUpTypes(this.state.currentLevel)
    if (availableTypes.length === 0) {
      return
    }

    const type = availableTypes[this.state.spawnCount % availableTypes.length]
    const lane = this.getRandomLane()
    const y = this.config.spawnHeight
    const laneX = this.getLaneX(x, lane)

    const powerUp = this.factory.createPowerUp(type, laneX, y)
    if (powerUp && this.entityManager) {
      this.entityManager.addEntity(powerUp)
      this.state.spawnCount++
    }
  }

  /**
   * 生成新的道具序列
   */
  private generateNewSequence(): void {
    const availableTypes = this.factory.getAvailablePowerUpTypes(this.state.currentLevel)
    this.state.currentSequence = []

    for (let i = 0; i < this.config.sequenceLength; i++) {
      const randomType = availableTypes[Math.floor(Math.random() * availableTypes.length)]
      this.state.currentSequence.push(randomType)
    }
  }

  /**
   * 获取随机车道
   */
  private getRandomLane(): number {
    const lanes = this.config.spawnLanes
    return lanes[Math.floor(Math.random() * lanes.length)]
  }

  /**
   * 获取车道X坐标
   */
  private getLaneX(baseX: number, lane: number): number {
    const laneWidth = 100 // 假设车道宽度为100像素
    const centerOffset = (lane - 1) * laneWidth // 车道0在左，车道1在中，车道2在右
    return baseX + centerOffset
  }

  /**
   * 获取生成距离
   */
  private getSpawnDistance(): number {
    const min = this.config.minSpawnDistance
    const max = this.config.maxSpawnDistance
    return min + Math.random() * (max - min)
  }

  /**
   * 获取生成统计信息
   */
  getStats(): {
    totalSpawned: number
    currentLevel: number
    currentSpawnRate: number
    lastSpawnTime: number
    pattern: PowerUpSpawnPattern
  } {
    const currentSpawnRate = this.config.baseSpawnRate + 
                           (this.state.currentLevel - 1) * this.config.spawnRateIncrease

    return {
      totalSpawned: this.state.spawnCount,
      currentLevel: this.state.currentLevel,
      currentSpawnRate,
      lastSpawnTime: this.state.lastSpawnTime,
      pattern: this.config.spawnPattern
    }
  }
}